package service

import (
	"fmt"
	"strconv"
	"time"

	"task/config"

	"github.com/gin-gonic/gin"
	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promauto"
)

var (
	requestTotal = promauto.NewCounterVec(
		prometheus.CounterOpts{
			Name: fmt.Sprintf("%s_request_total", config.Conf.TaskAdmin.Name),
			Help: "Number of task admin requests",
		},
		[]string{"path", "http_code"},
	)
	requestDuration = promauto.NewCounterVec(
		prometheus.CounterOpts{
			Name: fmt.Sprintf("%s_request_duration", config.Conf.TaskAdmin.Name),
			Help: "Duration of task admin requests",
		},
		[]string{"path", "http_code"},
	)
	requestLatency = promauto.NewSummaryVec(
		prometheus.SummaryOpts{
			Name:       fmt.Sprintf("%s_request_latency", config.Conf.TaskAdmin.Name),
			Help:       "Task admin request latency",
			Objectives: map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001},
		},
		[]string{"path", "http_code"},
	)
)

// metricsMiddlewares admin metrics middlewares.
func metricsMiddlewares() gin.HandlerFunc {
	return func(c *gin.Context) {
		start := time.Now()
		c.Next()
		path := c.Request.URL.Path
		httpCode := strconv.Itoa(c.Writer.Status())
		duration := float64(time.Since(start)) / float64(time.Millisecond)
		requestTotal.With(prometheus.Labels{
			"path":      path,
			"http_code": httpCode,
		}).Inc()
		requestDuration.With(prometheus.Labels{
			"path":      path,
			"http_code": httpCode,
		}).Add(duration)
		requestLatency.With(prometheus.Labels{
			"path":      path,
			"http_code": httpCode,
		}).Observe(duration)
	}
}
